package exercise_4;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class Test  {
	static void saveStaffToFile(Staff staff, File file) throws FileNotFoundException, IOException {
		FileOutputStream fos = new FileOutputStream(file,true);
		fos.write((staff.getName()+"/"+staff.getAge()+"/"+staff.getSalary()+'\n').getBytes());
		fos.close();
	}
	
	static List<Staff> readStaffFromFile(File file) throws FileNotFoundException, IOException {
		List<Staff> staffList = new ArrayList<>();
		BufferedReader bReader = new BufferedReader(new FileReader(file));
		String string = bReader.readLine();
		while(string != null) {
			String[] arr = string.split("/");
			System.out.println(arr[0]+arr[1]+arr[2]);
			staffList.add(new Staff(arr[0], Integer.valueOf(arr[1]), Double.valueOf(arr[2])));
			string = bReader.readLine();
		}
		bReader.close();
		System.out.println(staffList);
		return staffList;
	}
	public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
		Staff s1 = new Staff("s1", 21, 17000.0);
		Staff s2 = new Staff("s2", 22, 18000.0);
		
		ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("staff.txt"));
		oos.writeObject(s1);
		oos.writeObject(s2);
		oos.writeObject(null);
		oos.close();
		ObjectInputStream ois = new ObjectInputStream(new FileInputStream("staff.txt"));
		
		Staff staff;
		while((staff = (Staff)ois.readObject()) != null) {
			System.out.println("姓名"+staff.getName()+"年龄 "+ staff.getAge()+" 薪资:" +staff.getSalary());
		}
		File file = new File("method.txt"); 
		saveStaffToFile(s1, file);
		saveStaffToFile(s2, file);
		readStaffFromFile(file);
	}
}
